<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;

class UserRole extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function select()
    {
        //
		$userRole = Db::query('select group_concat(roles.name) as rName,group_concat(roles.id) as rid,ur.uname,ur.uid from roles right join 
		(select user.name as uname,user.id as uid,user_role.roleId from user left join user_role on user.id=user_role.userId ) ur
		on ur.roleId=roles.id group by ur.uid');
		return json($userRole);
    }

    public function addAndDel()
    {
        //
		$userId = input('post.userId');
		$needAdds = input('post.needAdd/a');
		$needDels = input('post.needDel/a');
		// return json('1'.gettype($needDels));
		Db::startTrans();
		try{
			// $resadd = [];
			// $resdel = [];
		foreach($needAdds as $needAdd){
			$r = Db::execute('insert into user_role (id,userId,roleId) values (null,?,?)',[$userId,$needAdd]);
			// $resadd[] = $needAdd;
		}
		foreach($needDels as $needDel){
			$r = Db::execute('delete from user_role where userId=? and roleId=?',[$userId,$needDel]);
			// $resdel[] = $needDel;
		}
		Db::commit();
		}catch(\Exception $e){
			Db::rollback();
			return json('数据回滚');
		}
		// $res=["add"=>$needAdd,"del"=>$needDel];
		// return json($res);
    }
		

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
